package net.xi.news.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.xi.news.dao.LogMapper;
import net.xi.news.pojo.Log;
import net.xi.news.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class LogServiceImpl extends ServiceImpl<LogMapper, Log> implements LogService {

    @Autowired
    private LogMapper logMapper;

    /**
     * 获得一个Log，如果没有就创建一个
     * @return
     */
    public Log getName(Integer type){
        Date date = new Date();
        DateFormat df1 = DateFormat.getDateInstance();//日期格式，精确到日
        System.out.println(df1.format(date));
        LambdaQueryWrapper<Log> queryWrapper= Wrappers.lambdaQuery();
        queryWrapper.eq(Log::getName,df1.format(date));
        queryWrapper.eq(Log::getType,type);
        Log log = logMapper.selectOne(queryWrapper);
        return log;
    }

    /**
     * 累加一次
     * @param type
     */
    @Override
    public void LogAdd(Integer type){
        Log log = getName(type);
        if (ObjectUtils.isEmpty(log)){
            Date date = new Date();
            DateFormat df1 = DateFormat.getDateInstance();//日期格式，精确到日
            System.out.println(df1.format(date));
            log = new Log();
            log.setType(type);
            log.setName(df1.format(date));
            log.setSum(1);
            logMapper.insert(log);
        }else {
            log.setSum(log.getSum()+1);
            logMapper.updateById(log);
        }
    }

    /**
     * 查询30天的记录
     * @param type
     * @return
     */
    @Override
    public List<Log> findLogByPage(Integer type){
        LambdaQueryWrapper<Log> queryWrapper=Wrappers.lambdaQuery();
        queryWrapper.eq(Log::getType,type);
        queryWrapper.orderByAsc(Log::getCreatetime);
        Page<Log> page=new Page<>(1,30);
        page = logMapper.selectPage(page, queryWrapper);
        return page.getRecords();
    }
}
